package com.yuyou.tas.lesson.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yuyou.tas.lesson.service.*;
import com.yuyou.tas.lesson.vo.req.ReqAddOrUpdateClass;
import com.yuyou.tas.lesson.vo.req.ReqUpdateClassPlanChapter;
import com.yuyou.tas.service.api.admin.dto.OfficeTokenDTO;
import com.yuyou.tas.service.api.admin.entity.AuthUser;
import com.yuyou.tas.service.api.admin.service.AuthUserAPI;
import com.yuyou.tas.service.api.lesson.dto.LessonChapterDetDTO;
import com.yuyou.tas.service.api.lesson.dto.LessonClassDTO;
import com.yuyou.tas.service.api.lesson.dto.LessonClassPageDTO;
import com.yuyou.tas.service.api.lesson.dto.LessonClassPlanChapterDTO;
import com.yuyou.tas.service.api.lesson.entity.Lesson;
import com.yuyou.tas.service.api.lesson.entity.LessonClass;
import com.yuyou.tas.service.api.lesson.entity.LessonClassChapter;
import com.yuyou.tas.util.bean.*;
import com.yuyou.tas.util.enums.admin.AuthUserEnums;
import com.yuyou.tas.util.enums.lesson.LessonEnums;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value="LessonController",description="班级操作接口")
@Validated
@RestController
@RequestMapping(value="/api/lessonClass")
public class LessonClassController extends BaseController {

    @Autowired
    private ILessonClassService lessonClassService;

    @Autowired
    private ILessonClassUserRelService lessonClassUserRelService;

	@Autowired
	private ILessonChapterService lessonChapterService;
	
	@Autowired
	private ILessonClassChapterService lessonClassChapterService;

	@Autowired
	private ILessonService lessonService;
    
    @Autowired
    private AuthUserAPI authUserAPI;

    @ApiOperation(value="班级管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dataSubject", value = "学科 id", paramType="query"),
            @ApiImplicitParam(name = "baseSectionId", value = "年级id", paramType="query"),
            @ApiImplicitParam(name = "baseTrimesterId", value = "学期id", paramType="query"),
            @ApiImplicitParam(name = "baseLevelId", value = "班型 id", paramType="query"),
            @ApiImplicitParam(name = "schoolId", value = "校区 id", paramType="query"),
            @ApiImplicitParam(name = "status", value = "班级状态 0未开课 ；1开课中；2已完结", paramType="query"),
            @ApiImplicitParam(name = "name", value = "班级名称", paramType="query"),
            @ApiImplicitParam(name = "lessonId", value = "课程id", paramType="query"),
            @ApiImplicitParam(name = "student", value = "学生名或编号", paramType="query"),
            @ApiImplicitParam(name = "tag", value = "是否通过授课班级获取：1、是，0或不传、否，2、通过用户校区权限过滤", paramType="query")
    })
    @RequestMapping(value="/findClassPage",method= RequestMethod.POST)
    public ReturnResult<Pagination<LessonClassPageDTO>> findClassPage(HttpServletRequest request,
                                                                      @Validated @ModelAttribute PageParams pageParams,
                                                                      Long dataSubject,
                                                                      Long baseSectionId,
                                                                      Long baseTrimesterId,
                                                                      Long baseLevelId,
                                                                      Long schoolId,
                                                                      Integer status,
                                                                      String name,
                                                                      Long lessonId,
                                                                      String student,
                                                                      Integer tag){
        LoginRedisObj loginObj = getUserObj(request);
        Pagination<LessonClassPageDTO> queryPgn = new Pagination<>();

        Map<String, Object> conditions=new HashMap<>();
        // 教务或管理员都能看到所有班级
        AuthUser authUser = authUserAPI.selectById(loginObj.getUserId());
        if(tag != null && tag == 1){
            conditions.put("isManage" , false);
        }else{
            conditions.put("isManage", (loginObj.getIsManager()
                    || AuthUserEnums.type.registrar.getValue() == authUser.getType()
                    || AuthUserEnums.type.headmaster.getValue() == authUser.getType()
                    || AuthUserEnums.type.other.getValue() == authUser.getType()) ? true : false);
            if(tag != null && tag == 2 && AuthUserEnums.schoolType.part.getValue() == authUser.getSchoolType()){
                conditions.put("schoolLimit", 2);
            }
        }
        conditions.put("authUserId", loginObj.getUserId());
        conditions.put("authOrganizationId",loginObj.getOrganizationId());
        conditions.put("dataSubject", dataSubject);
        conditions.put("baseSectionId", baseSectionId);
        conditions.put("baseTrimesterId", baseTrimesterId);
        conditions.put("baseLevelId", baseLevelId);
        conditions.put("schoolId", schoolId);
        conditions.put("status", status);
        conditions.put("name", name);
        conditions.put("lessonId", lessonId);
        conditions.put("student", student);
        queryPgn.setConditions(conditions);
        queryPgn.setPageParams(pageParams);
        int total = lessonClassService.findLessonClassPageCount(queryPgn);
        queryPgn.setTotal(total);
        queryPgn.toBePage();
        if(total > 0){
            queryPgn.setTotal(total);
            List<LessonClassPageDTO> list = lessonClassService.findLessonClassPageList(queryPgn);
            //判断该机构对应的科目年级权限
            if(!CollectionUtils.isEmpty(list)){
                list.forEach(lessonClassPageDTO -> {
                    if(lessonClassPageDTO.getLessonType() == LessonEnums.type.standard.getValue()
                            && (loginObj.getOrganSubSecMap() == null
                            || !loginObj.getOrganSubSecMap().containsKey(lessonClassPageDTO.getSubjectId())
                            || CollectionUtils.isEmpty(loginObj.getOrganSubSecMap().get(lessonClassPageDTO.getSubjectId()))
                            || !loginObj.getOrganSubSecMap().get(lessonClassPageDTO.getSubjectId()).contains(lessonClassPageDTO.getSectionId()))){
                        lessonClassPageDTO.setHasLessonPermit(0);
                    }else {lessonClassPageDTO.setHasLessonPermit(1);}
                });
            }

            queryPgn.setList(list);
        }
        return ReturnResult.success(queryPgn);
    }


    @ApiOperation(value = "新建或修改班级")
    @RequestMapping(value = "/addOrUpdateClass" ,method = RequestMethod.POST)
    public ReturnResult<LessonClass> addOrUpdateClass(HttpServletRequest request, @Validated @ModelAttribute ReqAddOrUpdateClass reqAddOrUpdateClass) throws Exception {

        LoginRedisObj loginObj = getUserObj(request);
        lessonClassService.addOrUpdateClass(reqAddOrUpdateClass, loginObj);
        return ReturnResult.success();
    }

    @ApiOperation(value = "删除班级")
    @RequestMapping(value = "/deleteLessonClass" ,method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "班级 ID", paramType = "query", required = true)})
    public ReturnResult<ResBoolSimpleInfo<String>> deleteLessonClass(Long id) {

//        ResBoolSimpleInfo<String> res = lessonClassService.deleteLessonClass(id);
//        return ReturnResult.success(res);
        return ReturnResult.fail("该功能暂未开放");
    }

    @ApiOperation(value = "班级详情")
    @RequestMapping(value = "/classDetail" ,method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "班级 ID", paramType = "query", required = true)})
    public ReturnResult<LessonClassDTO> classDetail(Long id){

        LessonClassDTO lessonClass = lessonClassService.getLessonClass(id);
        return ReturnResult.success(lessonClass);
    }

    @ApiOperation(value = "添加老师")
    @RequestMapping(value = "/addTeacher" ,method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "lessonClassId", value = "班级 id", paramType="query", required = true),
                        @ApiImplicitParam(name = "teacherId", value = "老师id", paramType="query", required = true),
                        @ApiImplicitParam(name = "type", value = "类型 0:主讲老师，1：代课老师", paramType="query", required = true),
                        @ApiImplicitParam(name = "lessonChapterId", value = "讲次id", paramType="query", required = false)
    })
    public ReturnResult<ResBoolSimpleInfo<String>> addTeacher(@NotNull(message = "班级ID不能为空") Long lessonClassId,
                                                              @NotNull(message = "老师ID不能为空")Long teacherId,
                                                              @NotNull(message = "类型不能为空")Integer type,
                                                              Long lessonChapterId){
        ResBoolSimpleInfo<String> res = lessonClassUserRelService.addTeacher(lessonClassId, teacherId, type, lessonChapterId);
        return ReturnResult.success(res);
    }

    @ApiOperation(value = "删除老师")
    @RequestMapping(value = "/deleteTeacher" ,method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "lessonClassId", value = "班级 id", paramType="query", required = true),
                        @ApiImplicitParam(name = "teacherId", value = "老师id", paramType="query", required = true),
                        @ApiImplicitParam(name = "type", value = "类型 0:主讲老师，1：代课老师", paramType="query", required = true),
                        @ApiImplicitParam(name = "lessonChapterId", value = "讲次id", paramType="query", required = false)
    })
    public ReturnResult<String> deleteTeacher(Long lessonClassId, Long teacherId, Integer type, Long lessonChapterId){

        ResBoolSimpleInfo<String> res = lessonClassUserRelService.deleteByClassIdUserId(lessonClassId, teacherId, type, lessonChapterId);
        return ReturnResult.success(res);
    }

    @ApiOperation(value = "更换老师")
    @RequestMapping(value = "/changeTeacher" ,method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "lessonClassId", value = "班级 id", paramType="query", required = true),
                        @ApiImplicitParam(name = "originTeacherId", value = "被更换老师id", paramType="query", required = true),
                        @ApiImplicitParam(name = "destTeacherId", value = "更换老师id", paramType="query", required = true),
                        @ApiImplicitParam(name = "type", value = "类型 0:主讲老师，1：代课老师", paramType="query", required = true),
                        @ApiImplicitParam(name = "lessonChapterId", value = "讲次id", paramType="query", required = false)
    })
    public ReturnResult<ResBoolSimpleInfo> changeTeacher(@NotNull(message = "lessonClassId 不能为空")Long lessonClassId,
                                                         @NotNull(message = "originTeacherId 不能为空")Long originTeacherId,
                                                         @NotNull(message = "destTeacherId 不能为空")Long destTeacherId,
                                                         @NotNull(message = "类型type 不能为空")Integer type,
                                                         Long lessonChapterId){
        ResBoolSimpleInfo<String> res = lessonClassUserRelService.changeTeacher(lessonClassId, originTeacherId, destTeacherId, type, lessonChapterId);
        return ReturnResult.success(res);
    }


    @ApiOperation(value = "班级讲次列表")
    @RequestMapping(value = "/lessonClassPlanChapterList" ,method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "班级 ID", paramType = "query", required = true)})
    public ReturnResult<List<LessonClassPlanChapterDTO>> lessonClassPlanChapterList(HttpServletRequest request,Long id){

        LoginRedisObj loginObj = getUserObj(request);
        Lesson l = lessonService.selectByClassId(id);
        //校验该机构对系统课程的年级科目权限
        if(l != null && LessonEnums.type.standard.getValue() == l.getType() && !loginObj.getIsSystem()
                &&(loginObj.getOrganSubSecMap() == null
                || !loginObj.getOrganSubSecMap().containsKey(l.getDataSubject())
                || CollectionUtils.isEmpty(loginObj.getOrganSubSecMap().get(l.getDataSubject()))
                || !loginObj.getOrganSubSecMap().get(l.getDataSubject()).contains(l.getBaseSectionId()))){
            return ReturnResult.success();
        }

        List<LessonClassPlanChapterDTO> lessonClassPlanChapterList = lessonClassService.lessonClassPlanChapterList(id);
        return ReturnResult.success(lessonClassPlanChapterList);
    }

	@ApiOperation(value = "班级讲次详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "lessonClassId", value = "班级 ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "lessonId", value = "课程 ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "lessonChapterId", value = "讲次ID", paramType = "query", required = true)
	})
	@RequestMapping(value = "/detailLessonClassChapter", method = {RequestMethod.POST })
	public ReturnResult<LessonChapterDetDTO> detailLessonClassChapter(HttpServletRequest request,
																	  @NotNull(message="班级 ID不能为空") Long lessonClassId,
																	  @NotNull(message="课程 ID不能为空") Long lessonId,
																	  @NotNull(message="讲次 ID不能为空") Long lessonChapterId){
		ResBoolSimpleInfo<LessonClassChapter> res = lessonChapterService.detailLessonClassChapter(lessonClassId, lessonId, lessonChapterId);
		return ReturnResult.returnRes(res);
	}

    @ApiOperation(value = "修改课表")
    @RequestMapping(value = "/updatePlanChapter" ,method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "updateClassPlanChapterJSON", value = "更新课表参数JSON", paramType = "query", required = true)})
    public ReturnResult<LessonClassDTO> updatePlanChapter(String updateClassPlanChapterJSON){

        List<ReqUpdateClassPlanChapter> classPlanChapterList = JSONObject.parseObject(updateClassPlanChapterJSON, new TypeReference<List<ReqUpdateClassPlanChapter>>(){});
        lessonClassService.updatePlanChapter(classPlanChapterList);
        return ReturnResult.success();
    }
    
    
    
    @ApiOperation(value = "复制课程讲次（课件，讲义）到班级讲次")
    @RequestMapping(value = "/copyLessonChapter" ,method = RequestMethod.POST)
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "lessonClassChapterId", value = "班级讲次ID", paramType = "query", required = true),
    	@ApiImplicitParam(name = "type", value = "类型(1:课件，2：讲义)", paramType = "query", required = true)
    	})
    public ReturnResult<OfficeTokenDTO> copyLessonChapter(HttpServletRequest request,
			  @NotNull(message="班级讲次ID不能为空") Long lessonClassChapterId,
			  @NotNull(message="类型不能为空") Integer type) throws Exception{    
    	
    	LoginRedisObj loginRedisObj=this.getUserObj(request);
    	ResBoolSimpleInfo<OfficeTokenDTO> res=lessonClassChapterService.copyLessonChapter(lessonClassChapterId,type,loginRedisObj);    
        return ReturnResult.returnRes(res);
    }
    
    
    
    
    
    
    
    
    
    
}
